package com.ntschy.sys.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ntschy.common.core.TreeSelect;
import com.ntschy.common.core.entity.dataobject.SysMenu;
import com.ntschy.common.core.entity.dataobject.SysRole;
import com.ntschy.common.core.entity.enums.SysMenuCache;
import com.ntschy.common.core.entity.enums.SysMenuTypeEnum;
import com.ntschy.common.core.entity.enums.SysMenuVisibleEnum;
import com.ntschy.common.core.entity.enums.SysWhetherEnum;
import com.ntschy.common.core.entity.vo.MetaVo;
import com.ntschy.common.core.entity.vo.RouterVo;
import com.ntschy.common.utils.SecurityUtils;
import com.ntschy.sys.mapper.SysMenuMapper;
import com.ntschy.sys.mapper.SysRoleMapper;
import com.ntschy.sys.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ezreal_geng
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    // * ================================================基础增删改查BEGIN============================================= *

    /**
     * 获取菜单列表
     * 当前查询条件：菜单名称 | 隐藏显示
     * @param menu 菜单对象
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> pageMenu(SysMenu menu) {
        List<SysMenu> menuList = null;
        if(SecurityUtils.getUser().isAdmin()) {
            menuList = menuMapper.pageMenuAll(menu);
        } else {
            menu.getParams().put("userId", SecurityUtils.getUser().getId());
            menuList = menuMapper.pageMenuByUserId(menu);
        }
        return menuList;
    }

    /**
     * 根据菜单ID获取菜单详情
     * @param menuId 菜单ID
     * @return 菜单
     */
    @Override
    public SysMenu fetchMenu(String menuId) {
        return menuMapper.selectById(menuId);
    }

    /**
     * 新增菜单
     * @param menu 菜单
     * @return 菜单
     */
    @Override
    public int addMenu(SysMenu menu) {
        menu.setId(IdUtil.fastUUID());
        return menuMapper.insert(menu);
    }

    /**
     * 根据id更新菜单
     * @param menu 菜单对象
     * @return 更新结果
     */
    @Override
    public int updateMenu(SysMenu menu) {
        return menuMapper.updateById(menu);
    }

    /**
     * 根据菜单ID删除菜单
     * @param menuId 菜单ID
     * @return 删除结果
     */
    @Override
    public int deleteMenu(String menuId) {
        return menuMapper.deleteById(menuId);
    }

    // * =================================================基础增删改查END============================================== *

    @Override
    public Set<String> listMenuPermsByUserId(String userId) {
        List<String> perms = menuMapper.listMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StrUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<String> listMenuIdByRoleId(String roleId) {
        SysRole role = roleMapper.selectById(roleId);
        return menuMapper.listMenuIdByRoleId(roleId, role.getMenuCheckStrictly().getValue());
    }

    @Override
    public List<SysMenu> listMenuTreeByUserId(String userId) {
        List<SysMenu> menus = null;
        if(SecurityUtils.isAdmin(userId)) {
            menus = menuMapper.listMenuTreeAll();
        } else {
            menus = menuMapper.listMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, "0");
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getIsCache() == SysMenuCache.NO, SysMenuVisibleEnum.HIDDEN == menu.getVisible(), menu.getActiveMenu()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && SysMenuTypeEnum.DIRECTORY == menu.getMenuType()) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getName(), menu.getIcon(), SysMenuCache.NO == menu.getIsCache(), SysMenuVisibleEnum.HIDDEN == menu.getVisible(), menu.getActiveMenu()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<String> tempList = new ArrayList<>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    //=================拼装路由方法区===========================

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = "Layout";
        if (StrUtil.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().equalsIgnoreCase("0") && SysMenuTypeEnum.MENU == menu.getMenuType()
                && menu.getIsFrame().equals(SysWhetherEnum.NO);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StrUtil.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (menu.getParentId().equalsIgnoreCase("0") && SysMenuTypeEnum.DIRECTORY == menu.getMenuType()
                && SysWhetherEnum.IS == menu.getIsFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }
    //=================拼装路由方法区===========================

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, String parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().equalsIgnoreCase(parentId)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().equalsIgnoreCase(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public boolean checkMenuNameExist(String menuName) {
        Integer rs = menuMapper.selectCount(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getName, menuName));
        return rs > 0;
    }

    @Override
    public boolean checkHasChildMenu(String menuId) {
        Integer rs = menuMapper.selectCount(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getParentId, menuId));
        return rs > 0;
    }

    @Override
    public boolean checkMenuExistRole(String menuId) {
        Integer rs = menuMapper.checkMenuExistRole(menuId);
        return rs > 0;
    }
}
